package boardgamer.yavalath.client.threads;

import android.util.Log;
import boardgamer.common.client.AbstractActivity;
import boardgamer.common.client.AbstractView;
import boardgamer.common.client.Logger;

import static com.google.common.base.Preconditions.checkNotNull;

public class UpdateThread implements Runnable {

  private final AbstractActivity<?> activity;
  private final AbstractView<?> view;
  private final GameThread gameThread;

  private long currentFrameTick = 0;

  public UpdateThread(AbstractView<?> view, AbstractActivity<?> activity, GameThread gameThread) {
    this.activity = checkNotNull(activity, "activity");
    this.view = checkNotNull(view, "view");
    this.gameThread = checkNotNull(gameThread, "gameThread");
  }

  @Override
  public void run() {
    currentFrameTick = System.currentTimeMillis();
    while (!Thread.interrupted()) {
      try {
        long elapsedTime = elapsedTime();
        switch (gameThread.getGameState()) {
          case STATE_RUN:
            activity.update((int) elapsedTime);
            view.update((int) elapsedTime);
            break;
          case STATE_PAUSE:
            Thread.sleep(100);
            break;
          default:
            break;
        }
      } catch (InterruptedException e) {
        Logger.log(Log.INFO, Log.getStackTraceString(e));
      } catch (Exception e) {
        Logger.log(Log.ERROR, Log.getStackTraceString(e));
      }
    }
  }

  private long elapsedTime() {
    long previousFrameTick = currentFrameTick;
    currentFrameTick = System.currentTimeMillis();
    return currentFrameTick - previousFrameTick;
  }
}
